<?php

namespace App\Http\Controllers\Home;

use App\Models\Comment;
use App\Models\Post;
use App\Models\Zan;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends BaseController
{
    //文章列表
    public function index()
    {
        $posts=Post::orderBy('created_at','desc')->withCount(['comments','zans'])->paginate(6);
        return view('post.index',compact('posts'));
    }
    //文章详情
    public function show(Post $post)
    {
        $post->load('comments');
        return view('post.show',compact('post'));
    }
    //添加文章
    public function create()
    {
        return view('post.add');
    }
    //添加文章行为
    public function store()
    {
        $this->validate(request(),[
            'title'=>'required|string|min:5|max:30',
            'content'=>'required|string|min:10'
        ]);
        $user_id=\Auth::id();
        $param=array_merge(request(['title','content']),compact('user_id'));
        Post::create($param);
        return redirect('/posts');
    }
    //编辑文章
    public function edit(Post $post)
    {
        //用户授权是否可以更新文章
       $this->authorize('update',$post);//TODO:用户认证返回值
        return view('post.edit',compact('post'));
    }
    //更新
    public function update(Post $post)
    {
        //验证
        $this->validate(request(),[
            'title'=>'required|string|min:5|max:30',
            'content'=>'required|string|min:10'
        ]);
        //用户授权是否可以更新文章
        $this->authorize('update',$post);
        //逻辑
        $post->title=request('title');
        $post->content=request('content');
        $post->save();
        //渲染
        return redirect("/posts/{$post->id}");
    }
    //删除
    public function delete(Post $post)
    {
        $this->authorize('delete',$post);//TODO 考虑抛出异常
        $post->delete();
        return redirect('/posts');
    }
    
    //上传图片
    public function imageupload(Request $request)
    {
        //TODO 判断文件上传大小 格式
        $path=$request->file('wangEditorH5File')->storePublicly(md5(time()));
        return asset('storage/'.$path);

    }
    //文章评论
    public function comment(Post $post)
    {
        $this->validate(request(),[
            'content'=>'required|string|min:3'
        ]);
        //TODO 自己不能给自己评论
        $comment=new Comment();
        $comment->user_id=\Auth::id();
        $comment->content=request('content');
        $post->comments()->save($comment);
        //渲染
        return back();
    }
    //文章攒
    public function zan(Post $post)
    {
        $param=[
            'user_id'=>\Auth::id(),
            'post_id'=>$post->id
        ];
        Zan::firstOrcreate($param);
        return back();
    }
    //取消攒
    public function unzan(Post $post)
    {
        $post->zan(\Auth::id())->delete();
        return back();
    }
    
    
}
